//
//  ChoosePhotoVC.m
//  ImGuider
//
//  Created by 李陆涛 on 2017/12/13.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "ChoosePhotoVC.h"
#import <TZImagePickerController.h>
#import <TZImageManager.h>
#import "UIView+Gradient.h"
#import "PlayerItem.h"

@interface ChoosePhotoVC () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, TZImagePickerControllerDelegate>

@property (nonatomic, strong) UIImagePickerController *imagePickerVC;

@property (nonatomic, weak) UIViewController *superVC;

@property (nonatomic, copy) void (^ selelctArrayBlock) (NSArray *phtoArray);

@end

@implementation ChoosePhotoVC

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [[PlayerItem playItemShareManager] hide];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [[PlayerItem playItemShareManager] show];
}

- (UIImagePickerController *)imagePickerVC {
    
    if (_imagePickerVC == nil) {
        _imagePickerVC = [[UIImagePickerController alloc] init];
        _imagePickerVC.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVC.navigationBar.barTintColor = kThemeColor;
        _imagePickerVC.navigationBar.tintColor = [UIColor whiteColor];
        _imagePickerVC.allowsEditing = self.allowsEditing;
    }
    return _imagePickerVC;
}

- (void)showWithViewController:(UIViewController *)vc selectArrayBlock:(void (^)(NSArray *))block {
    
    
    self.superVC = vc;
    self.selelctArrayBlock = block;
    
    [self addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) style:UIAlertActionStyleCancel handler:nil]];
    [self addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"MYINFO_CAMERA", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self pushImagePickerController];
    }]];
    
    [self addAction:[UIAlertAction actionWithTitle:MYLocalizedString(@"MYINFO_PHOTO", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self pushTZImagePickerController];
        
    }]];
    [vc presentViewController:self animated:YES completion:nil];
}


// 调用相机
- (void)pushImagePickerController {
    
    [[PlayerItem playItemShareManager] hide];
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        
        return;
    }
   
    [self getAuthorizationStatus];
}

- (void)getAuthorizationStatus {
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (authStatus == AVAuthorizationStatusDenied) {
        
        [IGAlertView alertWithTitle:@"" message:MYLocalizedString(@"PUBLIC_CAMERA_ALERT_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_NOGPS_ALERT_COMMIT", nil) commit:^{
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication] openURL:url];
        } cancel:nil];
        
        return;
    }
    
    self.imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePickerVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [self.superVC presentViewController:self.imagePickerVC animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [[PlayerItem playItemShareManager] show];
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        
        
        [tzImagePickerVc showProgressHUD];
        UIImage* originalImg = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        if (self.selelctArrayBlock) {
            self.selelctArrayBlock(@[originalImg]);
        }
    }
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    [[PlayerItem playItemShareManager] show];
}


#pragma mark - TZImagePickerController

- (void)pushTZImagePickerController {
    [[PlayerItem playItemShareManager] hide];
    
    PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
    
    if (authStatus == PHAuthorizationStatusDenied) {
        
        [IGAlertView alertWithTitle:@"" message:MYLocalizedString(@"PUBLIC_PHOTOS_ALERT_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_NOGPS_ALERT_COMMIT", nil) commit:^{
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication] openURL:url];
        } cancel:nil];
        
        return;
    }
    
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxCount columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    
    imagePickerVC.allowTakePicture = NO; // 在内部显示拍照按钮
    
    //    颜色
    
    imagePickerVC.naviTitleColor = [UIColor whiteColor];
    imagePickerVC.naviTitleFont = FontBold(18);
    
    //    UIView *barbgView = [[UIView alloc]initWithFrame:CGRectMake(0, -kStatusBarHeight, kScreenWidth, kNavigationBarHeight)];
    //    [barbgView gradientWithColorArray:@[kThemeDarkColor, kThemeLightColor] frame:CGRectMake(0, 0, kScreenWidth, kNavigationBarHeight) isLeftToRight:YES];
    
    //    [imagePickerVC.navigationBar setBackgroundImage:[barbgView convertToImage] forBarMetrics:UIBarMetricsDefault];
    
    
    
    //    图片
    //    @property (nonatomic, copy) NSString *photoSelImageName;
    //    @property (nonatomic, copy) NSString *photoDefImageName;
    
    //    @property (nonatomic, copy) NSString *photoOriginSelImageName;
    //    @property (nonatomic, copy) NSString *photoOriginDefImageName;
    
    //    @property (nonatomic, copy) NSString *photoPreviewOriginDefImageName;
    //    @property (nonatomic, copy) NSString *photoNumberIconImageName;
    imagePickerVC.photoSelImageName = @"button_tick_sel";
    //    imagePickerVC.photoDefImageName = @"button_tick_nor";
    
    imagePickerVC.photoOriginSelImageName = @"button_option_sel";
    imagePickerVC.photoOriginDefImageName = @"button_option_nor";
    
    imagePickerVC.photoNumberIconImageName = @"number_sel";
    
    
    
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVC.allowPickingVideo = NO;
    imagePickerVC.allowPickingImage = YES;
    
    imagePickerVC.allowPickingGif = NO;
    imagePickerVC.allowPickingMultipleVideo = NO; // 是否可以多选视频
    
    if (self.allowsEditing) {
        
        imagePickerVC.allowPickingOriginalPhoto = NO;
        imagePickerVC.allowCrop = YES;
        imagePickerVC.cropRect = CGRectMake(0, (kScreenHeight - kScreenWidth) / 2, kScreenWidth, kScreenWidth);
    } else {
        imagePickerVC.allowPickingOriginalPhoto = YES;
        imagePickerVC.allowCrop = NO;
        imagePickerVC.needCircleCrop = NO;
    }
    
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVC.showSelectBtn = NO;
    
    [self.superVC presentViewController:imagePickerVC animated:YES completion:nil];
}

#pragma mark - TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // IGLog(@"cancel");
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    
    [[PlayerItem playItemShareManager] show];
}

// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    if (self.selelctArrayBlock) {
        self.selelctArrayBlock(photos);
    }
    [[PlayerItem playItemShareManager] show]; 
}

// Decide album show or not't
// 决定相册显示与否
- (BOOL)isAlbumCanSelect:(NSString *)albumName result:(id)result {
    
    return YES;
}

// Decide asset show or not't
// 决定asset显示与否
- (BOOL)isAssetCanSelect:(id)asset {
    
    return YES;
}

@end

